package project.meetemup.view.profile;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import project.meetemup.model.Profile;
import project.meetemup.view.ActionBarActivity;
import project.meetemup.R;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.j256.ormlite.dao.Dao;

/**
 * Profile List Activity. Responsible for showing a list of profiles
 * @since 8/04/2012
 * @author João Paulo Mota
 */
public class ProfileListActivity extends ActionBarActivity {
	
    /**
     * Called when activity is created. Show a profile list to delete, edit or create a new profile
     */	
	public void onCreate(Bundle savedInstanceState) {     
		super.onCreate(savedInstanceState);
        setContentView(R.layout.profile_list);
        
        List<Profile> profileList = null;
        Profile profile = null;
    	Dao<Profile, Long> profileDao = null;
    	Iterator<Profile> profileIterator = null;
    	LinearLayout profileListLayout = (LinearLayout) findViewById(R.id.ProfileListLayout);
    	
    	try {
    		/**
    		 * get profile dao and query for all profiles in database
    		 */
			profileDao = getHelper().getProfileDao();
	    	profileList = profileDao.queryForAll();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    	if(profileList != null)
    		profileIterator = profileList.iterator();
    	
    	/**
    	 * iterate profile list and set a button one screen for each one
    	 */
    	if(profileIterator != null){
	    	while(profileIterator.hasNext()){
	    		profile = profileIterator.next();
	    		Button botao = new Button(this);
	    		botao.setText(profile.getName());
	    		botao.setTag(profile.getId());
	    		botao.setOnClickListener(new View.OnClickListener() {
		            public void onClick(View view) {
		                Intent myIntent = new Intent(view.getContext(), ProfileActivity.class);
		                myIntent.putExtra("selectedProfileId", (Long) view.getTag());
		                startActivityForResult(myIntent, 0);
		            }
	
		        });
	    		
	    		profileListLayout.addView(botao);
	    		
	    	}
    	}
    	
    	/**
    	 * 'create new profile' button
    	 */
		Button botao = new Button(this);
		botao.setText(R.string.new_profile);
		botao.setTag(null);
		botao.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), ProfileActivity.class);
                startActivityForResult(myIntent, 0);
            }

        });    	
    	
		profileListLayout.addView(botao);    	
    	
    	
	}

}
